use anyhow::Result;
use rand::distributions::Alphanumeric;
use rand::{thread_rng, Rng};
use std::iter;
use std::time::SystemTime;
use uuid::Uuid;

pub fn uuid() -> Result<String> {
    let a = Uuid::new_v4();
    Ok(a.to_string())
}

// random id bit with format time_6bitrandomnumber
pub fn id_generate_xbit(x: usize) -> String {
    let time = match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
        Ok(n) => format!("{}", n.as_millis()),
        Err(_) => format!(""),
    };
    let x = if x > 256 {
        256
    } else if x == 0 {
        1
    } else {
        x
    };
    // let s: String = rand::thread_rng()
    //     .sample_iter(&Alphanumeric)
    //     .take(6)
    //     .map(char::from)
    //     .collect();
    let mut rng = thread_rng();
    let s: String = iter::repeat(())
        .map(|()| rng.sample(Alphanumeric))
        .map(char::from)
        .take(x)
        .collect();
    format!("{}_{}", time, s)
}

#[cfg(test)]
mod tests {
    #[test]
    fn test_id_generate() {
        use crate::utils::ids;
        use crate::utils::logutil;

        logutil::global_log_init("coolink", "DEBUG");
        let id = ids::id_generate_xbit(6);
        log::info!("id = {}", id);

        assert_eq!(true, id.len() > 0);

        let uuid = ids::uuid();
        log::info!("id = {}", uuid.unwrap());
    }
}
